package com.tgy.leetcode;

import java.util.HashSet;

/**
 * @Author: tgy
 * @Date: 12/19/20 5:24 PM
 *
 *  https://leetcode-cn.com/problems/longest-consecutive-sequence/
 */
public class _128_最长连续序列 {

    public int longestConsecutive(int[] nums) {

        if (nums == null || nums.length == 0) {

            return 0;
        }

        // hashset已经去除重复数字了
        HashSet<Integer> sets = new HashSet<>();

        for (int num : nums) {

            sets.add(num);
        }

        int max = 0;

        for (int num : nums) {

            /**
             * 如果 存在 num-1,则会在num- 1 处开始会包含num
             */
            if (!sets.contains(num - 1)) {

                int tmp = 1;
                int tmpNum = num + 1;
                while (sets.contains(tmpNum)) {

                    tmpNum++;
                    tmp++;
                }

                if (max < tmp) {

                    max = tmp;
                }
            }

        }

        return max;
    }
}
